package com.ivncorp.evnproject;

import java.util.ArrayList;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ivncorp.evnproject.adapter.TimelineAdapter;
import com.ivncorp.evnproject.api.JSONParser;
import com.ivncorp.evnproject.api.RestAPI;
import com.ivncorp.evnproject.data.DataBaseHandler;
import com.ivncorp.evnproject.model.UploadTable;

public class FragmentTimeLine extends Fragment {

	TimelineAdapter adapter;
	ListView listv;
	Context context;
	ArrayList<UploadTable> data;
	PullToRefreshListView mPullRefreshListView;
	LinearLayout stconection;
	private NetworkChangeReceiver receiver;
	String label;
	DataBaseHandler db;
	public boolean isConnected;
	public String stConnected;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		IntentFilter filter = new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION);
		receiver = new NetworkChangeReceiver();
		db = new DataBaseHandler(getActivity());
		getActivity().registerReceiver(receiver, filter);

		label = DateUtils.formatDateTime(getActivity().getApplicationContext(),
				System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
						| DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_ABBREV_ALL);

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.fragment_timeline, container, false);
		stconection = (LinearLayout) v.findViewById(R.id.stconnection);

		mPullRefreshListView = (PullToRefreshListView) v
				.findViewById(R.id.pull_refresh_list);
		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						// Do work to refresh the list here.
						new AsyncLoadUploadTable().execute();
					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						Toast.makeText(getActivity(), "End of List!",
								Toast.LENGTH_SHORT).show();
					}
				});
		ListView actualListView = mPullRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);
		data = new ArrayList<UploadTable>();
		adapter = new TimelineAdapter(getActivity(), data);
		actualListView.setAdapter(adapter);

		new AsyncLoadUploadTable().execute();
		setHasOptionsMenu(true);
		return v;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// inflater.inflate(R.menu.fragment_sync, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	public class NetworkChangeReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(final Context context, final Intent intent) {
			isNetworkAvailable(context);
		}

		private boolean isNetworkAvailable(Context context) {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo[] info = connectivity.getAllNetworkInfo();
				if (info != null) {
					for (int i = 0; i < info.length; i++) {
						if (info[i].getState() == NetworkInfo.State.CONNECTED) {
							if (!isConnected) {
								if (info[i].getType() == ConnectivityManager.TYPE_WIFI)
									stConnected = "Now you are connected to Internet!+wifi";
								else if (info[i].getType() == ConnectivityManager.TYPE_MOBILE) {
									stConnected = "Now you are connected to Internet!+mobile";
								}
								isConnected = true;
								stconection.setVisibility(View.GONE);
								label = getResources().getString(R.string.dang_ket_noi);
							}
							return true;
						}
					}
				}
			}
			stConnected = "You are not connected to Internet!";
			label = "khong the ket noi";
			isConnected = false;
			stconection.setVisibility(View.VISIBLE);
			return false;
		}
	}

	protected class AsyncLoadUploadTable extends
			AsyncTask<Void, JSONObject, ArrayList<UploadTable>> {
		ArrayList<UploadTable> listUploadTable = null;

		@Override
		protected ArrayList<UploadTable> doInBackground(Void... params) {
			// TODO Auto-generated method stub

			if (isConnected) {
				RestAPI api = new RestAPI();
				try {

					
					JSONObject jsonObj = api.GetCotDauNois();

					JSONParser parser = new JSONParser();

					listUploadTable=parser.parseCotDauNoi(jsonObj);
					
					jsonObj = api.GetTrams();

					for (UploadTable item : parser.parseTram(jsonObj)) {
						listUploadTable.add(item);
					}
					jsonObj = api.GetTuTrungThes();

					for (UploadTable item : parser.parseTuTrungThe(jsonObj)) {
						listUploadTable.add(item);
					}


				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.d("AsyncLoadDeptDetails", e.getMessage());
				}
			} else {
				listUploadTable = db.getAllUploadTable();
			}
			return listUploadTable;
		}

		@Override
		protected void onPostExecute(ArrayList<UploadTable> result) {
			// TODO Auto-generated method stub

			if (result != null) {
				if (isConnected) {

					db.deleteAllData();
					for (int i = result.size() - 1; i >= 0; i--) {
						db.addUploadTable((new UploadTable(result.get(i)
								.getId(), result.get(i).getName(), result
								.get(i).getCode(),  result.get(i).getImage1(),
								result.get(i).getImage2(), result.get(i)
										.getImage3(),
										 result.get(i).getImage4(), result.get(i)
										.getImage5(), result.get(i)
										.getLatitude(), result.get(i)
										.getLongitude(), result.get(i)
										.getCapacity(),1)));

					}
				}

			}

			listUploadTable = db.getAllUploadTable();
			data.clear();
			data.addAll(listUploadTable);

			adapter.notifyDataSetChanged();
			mPullRefreshListView.onRefreshComplete();

			Intent intent = new Intent();
			intent.setAction("loadData");
			getActivity().sendBroadcast(intent);

		}
	}

}
